<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="安装https://www.mongodb.com/download-center 按照传统的方式，可以在这里下载mongo的安装包进行安装。 OSX如果是mac系统，并且按照了brew，可以直接执行brew install mongodb进行安装。 docker现在用docker快速的搭建软件环境已经非常方便了，所以我在这里将使用docker下载mongo的镜像来部署mongo，方便随后的测试。">
<meta name="keywords" content="Mongo">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB1-安装和增删改查">
<meta property="og:url" content="http://www.saily.top/2017/12/08/mongo1/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="安装https://www.mongodb.com/download-center 按照传统的方式，可以在这里下载mongo的安装包进行安装。 OSX如果是mac系统，并且按照了brew，可以直接执行brew install mongodb进行安装。 docker现在用docker快速的搭建软件环境已经非常方便了，所以我在这里将使用docker下载mongo的镜像来部署mongo，方便随后的测试。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/mongo/mongo1-1.png">
<meta property="og:updated_time" content="2018-01-07T11:48:34.680Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB1-安装和增删改查">
<meta name="twitter:description" content="安装https://www.mongodb.com/download-center 按照传统的方式，可以在这里下载mongo的安装包进行安装。 OSX如果是mac系统，并且按照了brew，可以直接执行brew install mongodb进行安装。 docker现在用docker快速的搭建软件环境已经非常方便了，所以我在这里将使用docker下载mongo的镜像来部署mongo，方便随后的测试。">
<meta name="twitter:image" content="http://www.saily.top/img/mongo/mongo1-1.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2017/12/08/mongo1/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>MongoDB1-安装和增删改查 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2017/12/08/mongo1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MongoDB1-安装和增删改查
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-08T14:37:05+08:00">12月 8 2017</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Mongo/" itemprop="url" rel="index"><span itemprop="name">Mongo</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p><a href="https://www.mongodb.com/download-center" target="_blank" rel="noopener">https://www.mongodb.com/download-center</a></p>
<p>按照传统的方式，可以在这里下载mongo的安装包进行安装。</p>
<h3 id="OSX"><a href="#OSX" class="headerlink" title="OSX"></a>OSX</h3><p>如果是mac系统，并且按照了brew，可以直接执行<code>brew install mongodb</code>进行安装。</p>
<h3 id="docker"><a href="#docker" class="headerlink" title="docker"></a>docker</h3><p>现在用docker快速的搭建软件环境已经非常方便了，所以我在这里将使用docker下载mongo的镜像来部署mongo，方便随后的测试。</p>
<p><a href="https://hub.docker.com/_/mongo/" target="_blank" rel="noopener">https://hub.docker.com/_/mongo/</a></p>
<a id="more"></a>
<p>dockerhub提供了官方镜像，我们选择好想要下载的版本，然后映射/data/db到我们本机的目录，<code>--auth</code>表示开启授权验证，mongo默认是不需要密码的，本机测试我们可以先不加这个参数。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker run --name my-mongo -v /Users/xiaomai/software/mongo:/data/db -d -p 27017:27017 -p 28017:28017 mongo:3.6.0 --auth</span><br></pre></td></tr></table></figure>
<p>因为是docker安装的，所以我们不能直接在本机上执行mongo命令来连接。</p>
<p>可以使用下面的命令来连接mongo：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker <span class="built_in">exec</span> -it my-mongo mongo <span class="built_in">test</span></span><br></pre></td></tr></table></figure>
<p>查看mongo的日志：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker logs -f my-mongo</span><br></pre></td></tr></table></figure>
<p>安装完毕。</p>
<h2 id="客户端连接工具"><a href="#客户端连接工具" class="headerlink" title="客户端连接工具"></a>客户端连接工具</h2><p>免费版：</p>
<p><a href="https://robomongo.org/download" target="_blank" rel="noopener">https://robomongo.org/download</a></p>
<p>收费版：</p>
<p><a href="https://studio3t.com/download/" target="_blank" rel="noopener">https://studio3t.com/download/</a></p>
<p>这是同一个公司开发的，目前是比较推荐这一款工具，非常好用。</p>
<p><img src="/img/mongo/mongo1-1.png" alt=""></p>
<h2 id="简单使用"><a href="#简单使用" class="headerlink" title="简单使用"></a>简单使用</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&gt; show dbs;</span><br><span class="line">admin   <span class="number">0.000</span>GB</span><br><span class="line">config  <span class="number">0.000</span>GB</span><br><span class="line">local   <span class="number">0.000</span>GB</span><br><span class="line">&gt; use test</span><br><span class="line">switched to db test</span><br><span class="line">&gt; db</span><br><span class="line">test</span><br><span class="line">&gt; show dbs;</span><br><span class="line">admin   <span class="number">0.000</span>GB</span><br><span class="line">config  <span class="number">0.000</span>GB</span><br><span class="line">local   <span class="number">0.000</span>GB</span><br></pre></td></tr></table></figure>
<p>查看数据库列表，切换了数据库，再次查看数据库列表，却发现没有新增的test数据库，这是mongo的特殊所在，现在的test只是一个临时数据库，再没有产生数据的时候，他不会被真正的创建只有当真正的插入数据的时候，数据库随之才会被创建。</p>
<h3 id="插入"><a href="#插入" class="headerlink" title="插入"></a>插入</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.hello.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">20</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; show dbs;</span><br><span class="line">admin   <span class="number">0.000</span>GB</span><br><span class="line">config  <span class="number">0.000</span>GB</span><br><span class="line">local   <span class="number">0.000</span>GB</span><br><span class="line">test    <span class="number">0.000</span>GB</span><br></pre></td></tr></table></figure>
<h3 id="查询"><a href="#查询" class="headerlink" title="查询"></a>查询</h3><p>查询一下刚才插入的数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.hello.find(&#123;&#125;)</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2a3af1e2beff69d97c54c3"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2a3b3ae2beff69d97c54c4"</span>), <span class="string">"name"</span> : <span class="string">"lisi"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br></pre></td></tr></table></figure>
<p>刚才插入的数据被查询出来了，mongodb用的就是JavaScript的语法，他们的数据也是用一种叫做bson的数据结构存储的，类似于json。</p>
<h4 id="id"><a href="#id" class="headerlink" title="_id"></a>_id</h4><p>这两条数据都有一个<strong>_id</strong>的字段，是mongo自动生成的主键/索引。</p>
<h3 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h3><p>删除数据的演示，{}里面可以加删除的过滤条件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.hello.remove(&#123;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nRemoved"</span> : <span class="number">2</span> &#125;)</span><br><span class="line">&gt; db.hello.find(&#123;&#125;).limit(<span class="number">1</span>);</span><br></pre></td></tr></table></figure>
<h3 id="修改"><a href="#修改" class="headerlink" title="修改"></a>修改</h3><h4 id="数据准备"><a href="#数据准备" class="headerlink" title="数据准备"></a>数据准备</h4><p>可以直接使用JS语法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; use mytest;</span><br><span class="line">switched to db mytest</span><br><span class="line">&gt; <span class="keyword">var</span> info = &#123;<span class="attr">name</span>: <span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">10</span>, <span class="attr">city</span>: <span class="string">'chengdu'</span>, <span class="attr">street</span>: <span class="string">'gaoxin'</span>&#125;;</span><br><span class="line">&gt; db.personalinfo.insert(info);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f847dcdf5d844e48cddb7"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">10</span>, <span class="string">"city"</span> : <span class="string">"chengdu"</span>, <span class="string">"street"</span> : <span class="string">"gaoxin"</span> &#125;</span><br></pre></td></tr></table></figure>
<h4 id="修改-1"><a href="#修改-1" class="headerlink" title="修改"></a>修改</h4><p>先把数据查出来：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">var</span> info = db.personalinfo.findOne(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;);</span><br><span class="line">&gt; info</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f847dcdf5d844e48cddb7"</span>),</span><br><span class="line">	<span class="string">"name"</span> : <span class="string">"zhangsan"</span>,</span><br><span class="line">	<span class="string">"age"</span> : <span class="number">10</span>,</span><br><span class="line">	<span class="string">"city"</span> : <span class="string">"chengdu"</span>,</span><br><span class="line">	<span class="string">"street"</span> : <span class="string">"gaoxin"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一样的用js语法对数据进行修改：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&gt; info.address = &#123;<span class="string">'city'</span>:info.city, <span class="string">'street'</span>:info.street&#125;;</span><br><span class="line">&#123; <span class="string">"city"</span> : <span class="string">"chengdu"</span>, <span class="string">"street"</span> : <span class="string">"gaoxin"</span> &#125;</span><br><span class="line">&gt; info.username = info.name;</span><br><span class="line">zhangsan</span><br><span class="line">&gt; info.userage = info.age;</span><br><span class="line"><span class="number">10</span></span><br><span class="line">&gt; <span class="keyword">delete</span> info.name;</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">&gt; <span class="keyword">delete</span> info.age;</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">&gt; <span class="keyword">delete</span> info.city;</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">&gt; <span class="keyword">delete</span> info.street;</span><br><span class="line"><span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>完成修改，update有4个参数，第一个是查询条件，第二个是替换的对象，还有两个参数是可选的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="string">'name'</span>:<span class="string">'zhangsan'</span>&#125;, info);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f847dcdf5d844e48cddb7"</span>), <span class="string">"address"</span> : &#123; <span class="string">"city"</span> : <span class="string">"chengdu"</span>, <span class="string">"street"</span> : <span class="string">"gaoxin"</span> &#125;, <span class="string">"username"</span> : <span class="string">"zhangsan"</span>, <span class="string">"userage"</span> : <span class="number">10</span> &#125;</span><br></pre></td></tr></table></figure>
<h4 id="修改器演示"><a href="#修改器演示" class="headerlink" title="修改器演示"></a>修改器演示</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.remove(&#123;&#125;);</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">10</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">20</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">30</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>, <span class="attr">age</span>:<span class="number">40</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">10</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br><span class="line">&gt; <span class="keyword">var</span> zhangsan = db.personalinfo.findOne(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>,<span class="attr">age</span>:<span class="number">10</span>&#125;);</span><br><span class="line">&gt; zhangsan.age++;</span><br><span class="line"><span class="number">10</span></span><br><span class="line">&gt; zhangsan.age</span><br><span class="line"><span class="number">11</span></span><br><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;, zhangsan);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">11</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br></pre></td></tr></table></figure>
<p>这里看到第一条记录被修改成了11岁。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; <span class="keyword">var</span> zhangsan = db.personalinfo.findOne(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>,<span class="attr">age</span>:<span class="number">40</span>&#125;);</span><br><span class="line">&gt; zhangsan.age++;</span><br><span class="line"><span class="number">40</span></span><br><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;, zhangsan);</span><br><span class="line">WriteResult(&#123;</span><br><span class="line">	<span class="string">"nMatched"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"nUpserted"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"nModified"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"writeError"</span> : &#123;</span><br><span class="line">		<span class="string">"code"</span> : <span class="number">66</span>,</span><br><span class="line">		<span class="string">"errmsg"</span> : <span class="string">"After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('5a2f8a32fd5fb3999c47142e')"</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>这次我们查询出40岁的张三，然后再次进行修改，这里得到一个错误，说_id不能被修改，说明update默认是条件过滤到的第一条数据来进行修改。</p>
<h5 id="inc修改器"><a href="#inc修改器" class="headerlink" title="$inc修改器"></a>$inc修改器</h5><p>我们可以用_id字段来进行简便的修改，这里用了$inc修改器，来对数值进行修改：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$inc</span>: &#123;<span class="attr">age</span>:<span class="number">1</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<h5 id="set修改器"><a href="#set修改器" class="headerlink" title="$set修改器"></a>$set修改器</h5><p>$set修改可以完成对属性的设定，如果属性不存在则添加，如果存在则修改。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$set</span>: &#123;<span class="attr">address</span>:<span class="string">'chengdu'</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span>, <span class="string">"address"</span> : <span class="string">"chengdu"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br></pre></td></tr></table></figure>
<p>同样的，$unset修改器可以删除一个属性。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$unset</span>: &#123;<span class="attr">address</span>:<span class="string">'chengdu'</span>&#125;&#125;);</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br></pre></td></tr></table></figure>
<h5 id="push修改器"><a href="#push修改器" class="headerlink" title="$push修改器"></a>$push修改器</h5><p>$push修改器可以对数组进行操作，增加一个books的属性，是一个数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$push</span>:&#123;<span class="attr">books</span>:<span class="string">'MongoDB'</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span>, <span class="string">"books"</span> : [ <span class="string">"MongoDB"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br></pre></td></tr></table></figure>
<h5 id="addToSet修改器"><a href="#addToSet修改器" class="headerlink" title="$addToSet修改器"></a>$addToSet修改器</h5><p>跟Java里的Set概念，如果是重复的数据，则不会被添加。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;_id:ObjectId(&apos;5a2f8a2afd5fb3999c47142b&apos;)&#125;, &#123;$addToSet:&#123;books:&apos;MongoDB&apos;&#125;&#125;);</span><br><span class="line">WriteResult(&#123; &quot;nMatched&quot; : 1, &quot;nUpserted&quot; : 0, &quot;nModified&quot; : 0 &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5a2f8a2afd5fb3999c47142b&quot;), &quot;name&quot; : &quot;zhangsan&quot;, &quot;age&quot; : 12, &quot;books&quot; : [ &quot;MongoDB&quot; ] &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5a2f8a2dfd5fb3999c47142c&quot;), &quot;name&quot; : &quot;zhangsan&quot;, &quot;age&quot; : 20 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5a2f8a30fd5fb3999c47142d&quot;), &quot;name&quot; : &quot;zhangsan&quot;, &quot;age&quot; : 30 &#125;</span><br><span class="line">&#123; &quot;_id&quot; : ObjectId(&quot;5a2f8a32fd5fb3999c47142e&quot;), &quot;name&quot; : &quot;zhangsan&quot;, &quot;age&quot; : 40 &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<p>我们再次为books属性添加了一个MongoDB的数据，跟我们期望的一样，重复的数据没有被添加。</p>
<h5 id="修改数组某一个值-（索引）"><a href="#修改数组某一个值-（索引）" class="headerlink" title="修改数组某一个值 （索引）"></a>修改数组某一个值 （索引）</h5><p>在需要修改数组中的某一个值的时候，还是可以用<code>$set</code>修改器来进行修改，只需要在key的后面加上一个索引。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$set</span>:&#123;<span class="string">'books.0'</span>:<span class="string">'Mongo'</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span>, <span class="string">"books"</span> : [ <span class="string">"Mongo"</span>, <span class="string">"JVM"</span> ] &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<h5 id="修改数组某一个值（根据查询条件）"><a href="#修改数组某一个值（根据查询条件）" class="headerlink" title="修改数组某一个值（根据查询条件）"></a>修改数组某一个值（根据查询条件）</h5><p>先把books改成一个对象的数组</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">_id</span>:ObjectId(<span class="string">'5a2f8a2afd5fb3999c47142b'</span>)&#125;, &#123;<span class="attr">$push</span>:&#123;<span class="string">'books'</span>:&#123;<span class="attr">name</span>:<span class="string">'Mongo'</span>, <span class="attr">price</span>:<span class="number">20</span>&#125;&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2afd5fb3999c47142b"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">12</span>, <span class="string">"books"</span> : &#123; <span class="string">"name"</span> : <span class="string">"Mongo"</span>, <span class="string">"price"</span> : <span class="number">20</span> &#125; &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a2dfd5fb3999c47142c"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">20</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a30fd5fb3999c47142d"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">30</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a2f8a32fd5fb3999c47142e"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">40</span> &#125;</span><br></pre></td></tr></table></figure>
<p>现在需要将books里mongo的价格改成30，但是不用索引。mongo为我们提供了一个$表示当前查询到的数据。<br>update的前两个参数&lt;查询条件&gt;和&lt;更新操作&gt;中，如果你在&lt;查询条件&gt;中查询的内容是array里的内容，&lt;更新操作&gt;中就可以使用”$”来引用前查询中匹配到的元素。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.personalinfo.update(&#123;<span class="string">'books.name'</span>:<span class="string">'Mongo'</span>&#125;, &#123;<span class="attr">$set</span>:&#123;<span class="string">'books.$.price'</span>:<span class="number">30</span>&#125;&#125;);</span><br></pre></td></tr></table></figure>
<h4 id="update参数详解"><a href="#update参数详解" class="headerlink" title="update参数详解"></a>update参数详解</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update</span><br><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">query, obj, upsert, multi</span>) </span>&#123;</span><br><span class="line">....</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>query表示查询条件</li>
<li>obj表示修改的对象</li>
<li>upsert表示更新或者插入</li>
<li>multi表示批量更新</li>
</ol>
<h5 id="upsert演示"><a href="#upsert演示" class="headerlink" title="upsert演示"></a>upsert演示</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.remove(&#123;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nRemoved"</span> : <span class="number">4</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a3130c1fd5fb3999c47142f"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span> &#125;</span><br><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;, &#123;<span class="attr">$inc</span>: &#123;<span class="attr">count</span>:<span class="number">3</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a3130c1fd5fb3999c47142f"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"count"</span> : <span class="number">3</span> &#125;</span><br></pre></td></tr></table></figure>
<p>直接修改不存在的属性，会新增一个属性。</p>
<p>这里查询了一个<code>lisi</code>的数据，默认情况下是不存在的，但是如果把upsert设置为true之后，就成了有数据就更新，没有就insert一条。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">name</span>:<span class="string">'lisi'</span>&#125;, &#123;<span class="attr">$inc</span>: &#123;<span class="attr">count</span>:<span class="number">3</span>&#125;&#125;);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">0</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">0</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">name</span>:<span class="string">'lisi'</span>&#125;, &#123;<span class="attr">$inc</span>: &#123;<span class="attr">count</span>:<span class="number">3</span>&#125;&#125;, <span class="literal">true</span>);</span><br><span class="line">WriteResult(&#123;</span><br><span class="line">	<span class="string">"nMatched"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"nUpserted"</span> : <span class="number">1</span>,</span><br><span class="line">	<span class="string">"nModified"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"_id"</span> : ObjectId(<span class="string">"5a31313f7cb00d3f6c6c4591"</span>)</span><br><span class="line">&#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a3130c1fd5fb3999c47142f"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"count"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a31313f7cb00d3f6c6c4591"</span>), <span class="string">"name"</span> : <span class="string">"lisi"</span>, <span class="string">"count"</span> : <span class="number">3</span> &#125;</span><br><span class="line">&gt;</span><br></pre></td></tr></table></figure>
<h5 id="批量更新"><a href="#批量更新" class="headerlink" title="批量更新"></a>批量更新</h5><p>先准备几条数据：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'zhangsan'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'beijing'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'lisi'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'guangzhou'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'wangwu'</span>,<span class="string">'age'</span>:<span class="number">20</span>,<span class="string">'address'</span>:<span class="string">'shanghai'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'zhaoliu'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'shenzhen'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</span><br></pre></td></tr></table></figure>
<p>把第4个参数设置成了true，表示执行批量更新</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.update(&#123;<span class="attr">age</span>:<span class="number">10</span>&#125;, &#123;<span class="attr">$set</span>:&#123;<span class="attr">company</span>:<span class="string">'sap'</span>&#125;&#125;, <span class="literal">false</span>, <span class="literal">true</span>);</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">3</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">3</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a48c6c9f0ec47e9f5ce2dac"</span>), <span class="string">"name"</span> : <span class="string">"zhangsan"</span>, <span class="string">"age"</span> : <span class="number">10</span>, <span class="string">"address"</span> : <span class="string">"beijing"</span>, <span class="string">"company"</span> : <span class="string">"sap"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a48c6c9f0ec47e9f5ce2dad"</span>), <span class="string">"name"</span> : <span class="string">"lisi"</span>, <span class="string">"age"</span> : <span class="number">10</span>, <span class="string">"address"</span> : <span class="string">"guangzhou"</span>, <span class="string">"company"</span> : <span class="string">"sap"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a48c6c9f0ec47e9f5ce2dae"</span>), <span class="string">"name"</span> : <span class="string">"wangwu"</span>, <span class="string">"age"</span> : <span class="number">20</span>, <span class="string">"address"</span> : <span class="string">"shanghai"</span> &#125;</span><br><span class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"5a48c6caf0ec47e9f5ce2daf"</span>), <span class="string">"name"</span> : <span class="string">"zhaoliu"</span>, <span class="string">"age"</span> : <span class="number">10</span>, <span class="string">"address"</span> : <span class="string">"shenzhen"</span>, <span class="string">"company"</span> : <span class="string">"sap"</span> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="save"><a href="#save" class="headerlink" title="save"></a>save</h3><p>mongo提供了一个save操作，它的行为取决于你是否传入了_id参数，如果你没有传，会洗澡一个，如果你传了_id，则会进行修改。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'_id'</span>:<span class="number">5</span>,<span class="string">'username'</span>:<span class="string">'zhangsan'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">0</span>, <span class="string">"nUpserted"</span> : <span class="number">1</span>, <span class="string">"nModified"</span> : <span class="number">0</span>, <span class="string">"_id"</span> : <span class="number">5</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.save(&#123;<span class="string">'_id'</span>:<span class="number">5</span>,<span class="string">'username'</span>:<span class="string">'lisi'</span>&#125;)</span><br><span class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</span><br><span class="line">&gt; db.personalinfo.find();</span><br><span class="line">&#123; <span class="string">"_id"</span> : <span class="number">5</span>, <span class="string">"username"</span> : <span class="string">"lisi"</span> &#125;</span><br><span class="line">&gt; db.personalinfo.insert(&#123;<span class="string">'_id'</span>:<span class="number">5</span>,<span class="string">'username'</span>:<span class="string">'lisi'</span>&#125;)</span><br><span class="line">WriteResult(&#123;</span><br><span class="line">	<span class="string">"nInserted"</span> : <span class="number">0</span>,</span><br><span class="line">	<span class="string">"writeError"</span> : &#123;</span><br><span class="line">		<span class="string">"code"</span> : <span class="number">11000</span>,</span><br><span class="line">		<span class="string">"errmsg"</span> : <span class="string">"E11000 duplicate key error collection: mytest.personalinfo index: _id_ dup key: &#123; : 5.0 &#125;"</span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="findAndModify"><a href="#findAndModify" class="headerlink" title="findAndModify"></a>findAndModify</h3><p>它是一种原子操作，正常情况下，查询并修改是两步操作，但是mongo为我们提供的这个函数，是原子性的，不会在多线程情况下出现并发问题。</p>
<blockquote>
<p>Modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option. </p>
</blockquote>
<p>修改并返回一个文档，默认是返回修改之前的文档，如果要返回修改之后的，设置<code>new</code>这个参数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">db.collection.findAndModify(&#123;</span><br><span class="line">    query: <span class="xml"><span class="tag">&lt;<span class="name">document</span>&gt;</span>,</span></span><br><span class="line">    sort: &lt;document&gt;,</span><br><span class="line">    remove: &lt;boolean&gt;,</span><br><span class="line">    update: &lt;document&gt;,</span><br><span class="line">    new: &lt;boolean&gt;,</span><br><span class="line">    fields: &lt;document&gt;,</span><br><span class="line">    upsert: &lt;boolean&gt;,</span><br><span class="line">    bypassDocumentValidation: &lt;boolean&gt;,</span><br><span class="line">    writeConcern: &lt;document&gt;,</span><br><span class="line">    collation: &lt;document&gt;,</span><br><span class="line">    arrayFilters: [ &lt;filterdocument1&gt;, ... ]</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>重要参数解释：</p>
<ul>
<li>query：查询参数</li>
<li>sort：排序的方式</li>
<li>remove：remove和update只能设置一个，删除查询条件筛选的内容</li>
<li>update：remove和update只能设置一个，修改查询条件筛选的内容</li>
<li>new：返回修改之后的文档</li>
<li>fields：表示返回的数据需要的字段</li>
</ul>
<h4 id="演示"><a href="#演示" class="headerlink" title="演示"></a>演示</h4><p>数据准备：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">db.personalinfo.remove(&#123;&#125;);</span><br><span class="line">db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'zhangsan'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'beijing'</span>&#125;)</span><br><span class="line">db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'lisi'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'guangzhou'</span>&#125;)</span><br><span class="line">db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'wangwu'</span>,<span class="string">'age'</span>:<span class="number">20</span>,<span class="string">'address'</span>:<span class="string">'shanghai'</span>&#125;)</span><br><span class="line">db.personalinfo.save(&#123;<span class="string">'name'</span>:<span class="string">'zhaoliu'</span>,<span class="string">'age'</span>:<span class="number">10</span>,<span class="string">'address'</span>:<span class="string">'shenzhen'</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>传入必要的参数，对数据进行修改，返回了修改成功的那一条数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&gt; db.personalinfo.findAndModify(&#123;</span><br><span class="line">...     query: &#123;<span class="attr">name</span>:<span class="string">'zhangsan'</span>&#125;,</span><br><span class="line">...     sort: &#123;<span class="attr">age</span>:<span class="number">-1</span>&#125;,</span><br><span class="line">...     remove: <span class="literal">false</span>,</span><br><span class="line">...     update:&#123;<span class="attr">$set</span>:&#123;<span class="attr">address</span>:<span class="string">'nanjing'</span>&#125;&#125;,</span><br><span class="line">...     new:<span class="literal">true</span></span><br><span class="line">... &#125;);</span><br><span class="line">&#123;</span><br><span class="line">	<span class="string">"_id"</span> : ObjectId(<span class="string">"5a48d102f0ec47e9f5ce2db0"</span>),</span><br><span class="line">	<span class="string">"name"</span> : <span class="string">"zhangsan"</span>,</span><br><span class="line">	<span class="string">"age"</span> : <span class="number">10</span>,</span><br><span class="line">	<span class="string">"address"</span> : <span class="string">"nanjing"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mongo/" rel="tag"># Mongo</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/11/30/git7/" rel="next" title="Git-cherry-pick、rebase">
                <i class="fa fa-chevron-left"></i> Git-cherry-pick、rebase
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/12/12/netty9/" rel="prev" title="Netty-编解码器&处理器">
                Netty-编解码器&处理器 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#OSX"><span class="nav-number">1.1.</span> <span class="nav-text">OSX</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#docker"><span class="nav-number">1.2.</span> <span class="nav-text">docker</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#客户端连接工具"><span class="nav-number">2.</span> <span class="nav-text">客户端连接工具</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#简单使用"><span class="nav-number">3.</span> <span class="nav-text">简单使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#插入"><span class="nav-number">3.1.</span> <span class="nav-text">插入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询"><span class="nav-number">3.2.</span> <span class="nav-text">查询</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#id"><span class="nav-number">3.2.1.</span> <span class="nav-text">_id</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除"><span class="nav-number">3.3.</span> <span class="nav-text">删除</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#修改"><span class="nav-number">3.4.</span> <span class="nav-text">修改</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#数据准备"><span class="nav-number">3.4.1.</span> <span class="nav-text">数据准备</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#修改-1"><span class="nav-number">3.4.2.</span> <span class="nav-text">修改</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#修改器演示"><span class="nav-number">3.4.3.</span> <span class="nav-text">修改器演示</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#inc修改器"><span class="nav-number">3.4.3.1.</span> <span class="nav-text">$inc修改器</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#set修改器"><span class="nav-number">3.4.3.2.</span> <span class="nav-text">$set修改器</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#push修改器"><span class="nav-number">3.4.3.3.</span> <span class="nav-text">$push修改器</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#addToSet修改器"><span class="nav-number">3.4.3.4.</span> <span class="nav-text">$addToSet修改器</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#修改数组某一个值-（索引）"><span class="nav-number">3.4.3.5.</span> <span class="nav-text">修改数组某一个值 （索引）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#修改数组某一个值（根据查询条件）"><span class="nav-number">3.4.3.6.</span> <span class="nav-text">修改数组某一个值（根据查询条件）</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#update参数详解"><span class="nav-number">3.4.4.</span> <span class="nav-text">update参数详解</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#upsert演示"><span class="nav-number">3.4.4.1.</span> <span class="nav-text">upsert演示</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#批量更新"><span class="nav-number">3.4.4.2.</span> <span class="nav-text">批量更新</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#save"><span class="nav-number">3.5.</span> <span class="nav-text">save</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#findAndModify"><span class="nav-number">3.6.</span> <span class="nav-text">findAndModify</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#演示"><span class="nav-number">3.6.1.</span> <span class="nav-text">演示</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
